#!/usr/bin/env python3
"""
手动导入Shopify产品到数据库
"""

import os
import sys
import logging
from datetime import datetime

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 导入数据库相关模块
from database.connection import async_session
from database.models import Product
import asyncio

async def import_manual_product():
    """手动导入产品到数据库"""
    logger.info("开始手动导入产品")
    
    async with async_session() as session:
        try:
            # 检查是否已存在同名产品
            logger.info("检查是否已存在同名产品...")
            from sqlmodel import select
            result = await session.execute(
                select(Product).where(Product.name == "modelCat")
            )
            existing_product = result.scalar_one_or_none()
            
            if existing_product:
                logger.info(f"产品 'modelCat' 已存在，ID: {existing_product.id}")
                logger.info("更新现有产品信息...")
                
                # 更新产品信息
                existing_product.name = "modelCat"
                existing_product.description = "比例模型套件"
                existing_product.price = 99.99
                existing_product.category_id = 1
                existing_product.stock_quantity = 2
                existing_product.is_active = True
                existing_product.shopify_product_id = "manual_import"
                existing_product.updated_at = datetime.utcnow()
                
                await session.commit()
                logger.info(f"产品更新成功，ID: {existing_product.id}")
            else:
                # 创建新产品
                logger.info("创建新产品 'modelCat'...")
                new_product = Product(
                    name="modelCat",
                    description="比例模型套件",
                    price=99.99,
                    category_id=1,
                    stock_quantity=2,
                    is_active=True,
                    shopify_product_id="manual_import",
                    created_at=datetime.utcnow(),
                    updated_at=datetime.utcnow()
                )
                
                session.add(new_product)
                await session.commit()
                await session.refresh(new_product)
                logger.info(f"产品创建成功，ID: {new_product.id}")
            
            # 验证导入结果
            result = await session.execute(
                select(Product).where(Product.name == "modelCat")
            )
            product = result.scalar_one_or_none()
            
            if product:
                logger.info("\n导入的产品信息:")
                logger.info(f"  ID: {product.id}")
                logger.info(f"  名称: {product.name}")
                logger.info(f"  描述: {product.description}")
                logger.info(f"  价格: {product.price}")
                logger.info(f"  库存: {product.stock_quantity}")
                logger.info(f"  状态: {'激活' if product.is_active else '未激活'}")
                logger.info("\n✓ 产品导入成功！")
                logger.info("请刷新后端管理页面查看产品")
            
        except Exception as e:
            logger.error(f"导入产品时发生错误: {e}")
            await session.rollback()
            import traceback
            traceback.print_exc()
        finally:
            await session.close()

if __name__ == "__main__":
    logger.info("=== 手动产品导入工具 ===")
    logger.info("从Shopify后台导入 'modelCat' 产品到数据库")
    asyncio.run(import_manual_product())